package com.base.thread.demo_13;

/**
 * 序列生成器
 * @ClassName: Sequence
 * @Description: 
 * @Author xuyou
 * @DateTime 2019年12月7日 下午4:07:03
 */
public class Sequence {
	
	private int value;
	
	public int getNext() {
		return value ++;
	}
//		在cmd中使用 javap -verbose Sequence.class 可以查看字节码指令
//        5: aload_0
//        6: getfield      #18   // Field value:I
//        9: ifle          19
//       12: aload_0
//       13: getfield      #18  // Field value:I
//       16: aload_1
	
	public static void main(String[] args) {
		
		Sequence s = new Sequence();
		// 单线程执行getNext 不会出现生成重复的数
//		while(true) {
//			System.out.println(s.getNext());
//		}
	
		//多个线程执行 会出现重复的数
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true) {
					System.out.println(Thread.currentThread().getName() + " " + s.getNext());
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
	}

}
